package queue;

import org.junit.Test;

import java.util.concurrent.*;

/**
 * @author zhangxin
 * @date 2020/9/28
 */
public class BlockQueueTest {

    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(2);
        queue.add("java");
        queue.add("py");


        new LinkedBlockingQueue<String>();

        // 优先级无界
        PriorityBlockingQueue priorityBlockingQueue = new PriorityBlockingQueue(1);
        priorityBlockingQueue.add("java");
        priorityBlockingQueue.add("java2");
    }


    public void linkedBlockQuere() {
        LinkedBlockingQueue<Object> objects = new LinkedBlockingQueue<>();

    }

    @Test
    public void syn() throws InterruptedException {
        // 每个put操作都必须等待一个take操作完成，否则不能继续添加元素
        SynchronousQueue<Object> synchronousQueue = new SynchronousQueue<>();

        new Thread(() -> {
            while (true) {
                try {
                    Object take = synchronousQueue.take();
                    System.out.println(take);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        sleep(2000);

        synchronousQueue.add("java");
    }

    @Test
    public void linkedTransfer() throws InterruptedException {
        LinkedTransferQueue<Object> linkedTransferQueue = new LinkedTransferQueue<>();

        new Thread(() -> {
            try {
                linkedTransferQueue.transfer("java");
                linkedTransferQueue.transfer("java2");
                linkedTransferQueue.transfer("java3");
                linkedTransferQueue.transfer("java4");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        //sleep(2000);
        new Thread(() -> {
            while (true) {
                try {
                    Object take = linkedTransferQueue.take();
                    Thread.sleep(1000L);
                    System.out.println(take);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Thread.currentThread().join();
    }


    private void sleep(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testArrayLinked() {
        ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(2);

        for (int i = 0; i < 10; i++) {
            queue.offer("q" + i);
        }
        String str;
        while ((str = queue.poll() )!= null) {
            System.out.println(str);
        }
    }
}
